package com.ruoyi.project.system.user.controller;

import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@Slf4j
@Controller
public class LoginController extends BaseController
{
    @GetMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response)
    {
        // 如果是Ajax请求，返回Json字符串。
        if (ServletUtils.isAjaxRequest(request))
        {
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"未登录或登录超时。请重新登录\"}");
        }

        return "login";
    }

    @PostMapping("/login")
    @ResponseBody
    public AjaxResult ajaxLogin(String username, String password, Boolean rememberMe)
    {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        Subject subject = SecurityUtils.getSubject();
        try
        {
            subject.login(token);
            return success();
        }
        catch (AuthenticationException e)
        {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage()))
            {
                msg = e.getMessage();
            }
            return error(msg);
        }
    }

    /**
     * sm4测试
     */
    @GetMapping("/testSm4")
    @ResponseBody
    public String testSm4(@RequestParam("userName") String userName) {
        SymmetricCrypto sm4 = SmUtil.sm4("f4870383c764a059".getBytes(StandardCharsets.UTF_8));
        byte[] bytes = ("{\"phone\":\"" + userName + "\",\"timestamp\":" + System.currentTimeMillis() + "}").getBytes();
        byte[] encrypt = sm4.encrypt(bytes);
        return new String(Hex.encodeHex(encrypt));
    }

    /**
     * 接入山东通sso登录
     */
    @Value("${sso.keySecret}")
    private String keySecret;
    @RequestMapping("/ssoLogin")
    public String ssoLogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取参数code
        String code = request.getParameter("code");
        //解密
        SymmetricCrypto sm4 = SmUtil.sm4(keySecret.getBytes(StandardCharsets.UTF_8));
        JSONObject jsonObject = JSON.parseObject(sm4.decryptStr(code));
        //获取用户手机号
        String phone = jsonObject.getString("phone");
        //获取时间戳
        long timestamp = jsonObject.getLongValue("timestamp");
        Date date = new Date(timestamp);
        Calendar accessTime = Calendar.getInstance();
        Calendar currentTime = Calendar.getInstance();
        accessTime.setTime(date);//要判断的日期
        currentTime.setTime(new Date());//初始日期
        currentTime.add(Calendar.MINUTE, -5);//减去五分钟
        if (accessTime.after(currentTime)) {
            log.info("5分钟以内，登录令牌有效");
            // 用户验证
            UsernamePasswordToken token = new UsernamePasswordToken(Constants.SSO_USERNAME_PREFIX + phone, Constants.SSO_PASSWORD);
            Subject subject = SecurityUtils.getSubject();
            try{
                subject.login(token);
            }
            catch (AuthenticationException e){
                return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"账号或密码错误，SSO登录失败\"}");
            }
            // 用户登录逻辑

            //跳转系统业务页面
            // response.sendRedirect(frontPageUrl);
            return "social/socialSearch";
        } else {
            log.info("超过5分钟，登录令牌失效");
            // 自行定义错误页面
            // 如果账号错误、有效时间超时、或者解析异常，跳转平台相应的错误页面
            // 如果模块有值，则跳转到登记的模块地址
            // response.sendRedirect("errorPage");
            return ServletUtils.renderString(response, "{\"code\":\"1\",\"msg\":\"超过5分钟，登录令牌失效。请重新登录\"}");
        }
    }
    @GetMapping("/unauth")
    public String unauth()
    {
        return "error/unauth";
    }
}
